import { spawn } from 'child_process';
import { promises as fs } from 'fs';
import path from 'path';
import common from "../../lib/common/common.js"

const scriptCache = new Map();

async function findPythonScript(scriptName) {
    if (scriptCache.has(scriptName)) {
        return scriptCache.get(scriptName);
    }

    const startDir = process.cwd();
    const targetFile = `${scriptName}.py`;
    let foundPath = null;

    async function searchDirectory(dir) {
        try {
            const entries = await fs.readdir(dir, { withFileTypes: true });
            
            for (const entry of entries) {
                const fullPath = path.join(dir, entry.name);
                
                if (entry.isDirectory()) {
                    await searchDirectory(fullPath);
                } else if (entry.isFile() && entry.name === targetFile) {
                    foundPath = fullPath;
                    return; 
                }
            }
        } catch (err) {
            console.error(`搜索目录时出错: ${dir}`, err);
        }
    }

    await searchDirectory(startDir);
    
    if (foundPath) {
        scriptCache.set(scriptName, foundPath); 
        return foundPath;
    }
    
    return null; 
}

const main = async (id, name, e) => {
    try {
        const scriptPath = await findPythonScript(name);
        
        if (!scriptPath) {
            return e.reply(`未找到${name}.py脚本`);
        }

        const pythonProcess = spawn('python', [scriptPath], {
            cwd: path.dirname(scriptPath)
          });
        pythonProcess.stdout.setEncoding('utf8');
        pythonProcess.stderr.setEncoding('utf8');
        
        let stdoutBuffer = '';
        let stderrBuffer = '';
        
        pythonProcess.stdout.on('data', (data) => {
            stdoutBuffer += data;
        });
        
        pythonProcess.stderr.on('data', (data) => {
            stderrBuffer += data;
        });
        
        pythonProcess.on('close', (code) => {
            if (stdoutBuffer) {
                let msg = []
                msg.push(
                    [
                         `${stdoutBuffer}`
                    ]
                );
                e.reply(common.makeForwardMsg(e, msg, `好东西`));
                e.reply("ok");
            }
            if (stderrBuffer) {
                console.error(`错误信息: ${stderrBuffer}`);
            }
            console.log(`进程退出，状态码: ${code}`);
        });
        
        pythonProcess.stdin.write(Buffer.from(id, 'utf8'));
        pythonProcess.stdin.end();
    } catch (err) {
        console.error('执行Python脚本时出错:', err);
        e.reply('执行Python脚本时出错');
    }
};

export class YTJM extends plugin {
    constructor() {
        super({
            name: '阴天JM',
            dsc: '阴天JM',
            event: 'message',
            priority: 5000,
            rule: [
                {
                    reg: '^#?阴天看jm\\s*(.*)',
                    fnc: 'YTJMK'
                }, 
                {
                    reg: '^#?阴天搜jm\\s*(.*)',
                    fnc: 'YTJMS'
                },
            ]
        })
    }
    
    async YTJMK(e) {
        const id = e.msg.replace(/^#?阴天看jm\s*/, "").trim();
        if (!id) return e.reply("请输入JMID");
        await main(id, "YTJM", e);
    }
    
    async YTJMS(e) {
        const TAG = e.msg.replace(/^#?阴天搜jm\s*/, "").trim();
        if (!TAG) return e.reply("请输入搜索tag");
        await main(TAG, "YTJM2", e);
    }
}